package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.annotation.AutoFill;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.enumeration.OperationType;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmalDishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/*
 * 菜品管理的service
 * service层的作用：
 *   调用mapper层的方法查询数据库，如果需要将查询到的数据进行逻辑处理就在service层处理
 *   返回结果给Controller层
 * */
@Service
public class DishServiceImp implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmalDishMapper setmalDishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    /**
     * 查询所有菜品
     *
     * @param dishPageQueryDTO
     * @return pageResult
     * @info 接收Controller层传递过来的分页参数，Service层再去调用Mapper层的方法去数据库中查询所有分类  Service->Mapper
     */
    @Override
    public PageResult fetchDishList(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> page = (Page<DishVO>) dishMapper.selectDishList(dishPageQueryDTO);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 起售和停售菜品
     *
     * @param status
     * @param id
     * @return void
     * @info 接收Controller层传递过来的status和id，Service层再去调用Mapper层的方法去数据库中修改状态  Service->Mapper
     */
    @Override
    @AutoFill(value = OperationType.UPDATE)
    public void updateDishStatus(Integer status, Long id) {
        Dish dish = new Dish();
        dish.setId(id);
        dish.setStatus(status);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.updateDishStatus(dish);
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return void
     * @info 接收Controller层传递过来的ids，Service层再去调用Mapper层的方法去数据库中删除菜品  Service->Mapper
     */
    @Override
    @Transactional
    public void deleteDishById(String ids) {
        /*是否存在起售的菜品*/
        List<Dish> dishesList = dishMapper.selectDishListByIds(ids);
        for (Dish dish : dishesList) if (dish.getStatus() == 1) throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        /*是否被套餐关联了*/
        List<Long> setmealIdList = setmalDishMapper.selectSetmealIdList(ids);
        if (setmealIdList.size() > 0 && setmealIdList != null) throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        // 删除菜品数据
        dishMapper.deleteDishById(ids);
        // 删除菜品下的口味数据
        dishFlavorMapper.deleteDishFlavorByDishId(ids);
    }

    /**
     * 根据id查询菜品和口味
     *
     * @param id
     * @return dishVO
     * @info 接收Controller层传递过来的id，Service层再去调用Mapper层的方法去数据库中查询菜品和口味数据  Service->Mapper
     */

    public DishVO fetchDishAndFlavor(Long id) {
        // 根据id查询菜品
        Dish dish = dishMapper.selectDishById(id);
        // 根据菜品id查询口味
        List<DishFlavor> dishFlavorList = dishFlavorMapper.gselectDishFlavorByDishId(id);
        //创建dishvo对象
        DishVO dishVO = new DishVO();
        // 对象拷贝
        BeanUtils.copyProperties(dish, dishVO);
        // 设置口味数据
        dishVO.setFlavors(dishFlavorList);
        // 返回给Controller层
        return dishVO;
    }


    /**
     * 添加菜品
     *
     * @param dishDTO
     * @return void
     * @info 接收Controller层传递过来的菜品，Service层再去调用Mapper层的方法去数据库中添加菜品  Service->Mapper
     */
    @Override
    @Transactional
    public void addDish(DishDTO dishDTO) {
        /*
         * 进行菜品的添加
         * */
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setCreateTime(LocalDateTime.now());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setStatus(1);
        dishMapper.insertDish(dish);

        /*
         * 进行菜品所属的口味添加
         * */
        List<DishFlavor> dishFlavorList = dishDTO.getFlavors();

        // 获取insert语句插入数据库后的主键ID
        Long dishId = dish.getId();


        if (dishFlavorList != null && dishFlavorList.size() > 0) {
            dishFlavorList.forEach(dishFlavor -> dishFlavor.setDishId(dishId));
            dishFlavorMapper.insertBatchDishFlavor(dishFlavorList);
        }
    }

    public void updateDish(DishDTO dishDTO) {
        /*修改菜品*/
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.updateDish(dish);


        // 先删除所有id匹配的口味数据
        dishFlavorMapper.deleteDishFlavorByDishId(dishDTO.getId() + "");

        /*批量插入口味数据*/
        List<DishFlavor> dishFlavorList = dishDTO.getFlavors();
        if (dishFlavorList != null && dishFlavorList.size() > 0) {
            dishFlavorList.forEach(dishFlavor -> dishFlavor.setDishId(dish.getId()));
            dishFlavorMapper.insertBatchDishFlavor(dishFlavorList);
        }
    }

    /**
     * 根据分类id查询菜品
     *
     * @param categoryId
     * @return
     */
    public List<Dish> list(Long categoryId) {
        List<Dish> dishList = dishMapper.fetchDishByCategoryId(categoryId);
        return dishList;
    }
}
